from tkinter import *
from tkinter.ttk import Combobox
from update import (is_update_needed, update_repository)
import threading
import json


# 读取 JSON 数据
def load_items_from_json(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    return data['items']


# 主窗口初始化
root = Tk()
root.geometry('1200x700')
root.title('三角洲生产物品单小时利润计算器')
root.geometry('+200+50')


# 更新提示函数
def UpdatePrompt(is_manual_check=False):
    repo_path = './lukas-data'
    if is_update_needed(repo_path):
        popup = Toplevel(root)
        popup.title("提示")
        label = Label(popup, text="有更新哟，是否更新？")
        label.pack(padx=40, pady=10)

        x = root.winfo_x() + 400
        y = root.winfo_y() + 100
        popup.geometry(f"+{x}+{y}")

        def on_update():
            popup.destroy()

            progress_popup = Toplevel(root)
            progress_popup.title("更新中")
            label = Label(progress_popup, text="正在更新，请稍候...")
            label.pack(padx=40, pady=20)
            progress_popup.update()

            x = root.winfo_x() + 400
            y = root.winfo_y() + 100
            progress_popup.geometry(f"+{x}+{y}")

            update_repository(repo_path)

            progress_popup.destroy()

            done_popup = Toplevel(root)
            done_popup.title("提示")
            label = Label(done_popup, text="更新已完成！")
            label.pack(padx=60, pady=20)

            x = root.winfo_x() + 400
            y = root.winfo_y() + 100
            done_popup.geometry(f"+{x}+{y}")

        def on_cancel():
            popup.destroy()

        Button(popup, text="更新", command=on_update).pack(side=LEFT, padx=10, pady=10)
        Button(popup, text="取消", command=on_cancel).pack(side=RIGHT, padx=10, pady=10)

        x = root.winfo_x() + 400
        y = root.winfo_y() + 100
        popup.geometry(f"+{x}+{y}")

    elif is_manual_check:
        no_update_popup = Toplevel(root)
        no_update_popup.title("提示")
        label = Label(no_update_popup, text="当前已经是最新版本。")
        label.pack(padx=40, pady=20)

        x = root.winfo_x() + 400
        y = root.winfo_y() + 100
        no_update_popup.geometry(f"+{x}+{y}")


# 添加检测更新按钮
update_button_in_main = Button(
    root,
    text="检测更新",
    command=lambda: UpdatePrompt(is_manual_check=True)
)
update_button_in_main.place(relx=1.0, rely=1.0, x=-20, y=-20, anchor='se')

def check_for_update_in_background():
    repo_path = './lukas-data'
    if is_update_needed(repo_path):
        # 使用 root.after() 回调到主线程再创建弹窗
        root.after(0, lambda: UpdatePrompt(is_manual_check=False))

# 启动后台线程来检测更新
threading.Thread(target=check_for_update_in_background).start()

# ===================== 四个分区数据加载 =====================
json_files = [
    ('枪械/配件', './lukas-data/data-gun.json'),
    ('子弹', './lukas-data/data-bullet.json'),
    ('药品', './lukas-data/data-medicine.json'),
    ('防具', './lukas-data/data-armor.json'),
]

panels = []

for idx, (title, file_path) in enumerate(json_files):
    row = idx // 2
    col = idx % 2

    # 创建一个 Frame 作为分区容器
    frame = LabelFrame(root, text=title, font=("微软雅黑", 12))
    frame.grid(row=row, column=col, padx=20, pady=10, sticky='nsew')

    # 加载数据
    items = load_items_from_json(file_path)
    item_names = [item['name'] for item in items]

    current_item = [None]
    profit_input_var = StringVar()

    # 检索 + 下拉选择组件
    search_var = StringVar()
    search_entry = Entry(frame, textvariable=search_var)
    search_entry.pack(pady=5)

    combobox = Combobox(frame, textvariable=search_var, values=item_names, state='readonly')
    combobox.pack(pady=5)

    # 利润输入框
    profit_frame = Frame(frame)
    profit_frame.pack(pady=5)
    Label(profit_frame, text="总利润：").pack(side=LEFT)
    profit_entry = Entry(profit_frame, textvariable=profit_input_var, width=10)
    profit_entry.pack(side=LEFT)

    # 显示区
    selected_frame = Frame(frame)
    selected_frame.pack(pady=10)


    def make_display_func(selected_frame, current_item, profit_input_var):
        def display_current_item():
            for widget in selected_frame.winfo_children():
                widget.destroy()

            if current_item[0]:
                item = current_item[0]
                profit_text = profit_input_var.get()

                try:
                    total_profit = float(profit_text) if profit_text else 0
                    hourly_profit = round(total_profit / item['time'], 2) if item['time'] > 0 else 0
                except ValueError:
                    hourly_profit = "无效数值"

                Label(selected_frame, text="名称：" + item['name']).pack(anchor='w')
                Label(selected_frame, text=f"耗时：{item['time']} 小时").pack(anchor='w')
                Label(selected_frame, text=f"总利润：{profit_text} 哈夫币").pack(anchor='w')
                Label(selected_frame, text=f"小时利润：{hourly_profit} 哈夫币/小时").pack(anchor='w')

        return display_current_item


    display_func = make_display_func(selected_frame=selected_frame,
                                     current_item=current_item,
                                     profit_input_var=profit_input_var)


    def on_item_selected(event, items=items, current_item=current_item, display_func=display_func):
        selected_name = combobox.get()
        selected_item = next((item for item in items if item['name'] == selected_name), None)
        if selected_item:
            current_item[0] = selected_item
            display_func()


    def update_combobox(*args, item_names=item_names, combobox=combobox):
        search_term = search_var.get().lower()
        filtered = [name for name in item_names if search_term in name.lower()]
        combobox['values'] = filtered


    search_var.trace_add("write", lambda *a, func=update_combobox: func())


    def make_on_item_selected_handler(items, current_item, display_func, combobox):
        def handler(event):
            selected_name = combobox.get()  # 使用传入的 combobox
            selected_item = next((item for item in items if item['name'] == selected_name), None)
            if selected_item:
                current_item[0] = selected_item
                display_func()

        return handler


    combobox.bind("<<ComboboxSelected>>",
                  make_on_item_selected_handler(items, current_item, display_func, combobox))

    profit_input_var.trace_add("write", lambda *a, func=display_func: func())

    panels.append({
        'frame': frame,
        'search_var': search_var,
        'combobox': combobox,
        'profit_input_var': profit_input_var,
        'current_item': current_item,
        'display': display_func
    })


# 设置网格列权重，使布局更美观
root.rowconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)



# 运行主循环
root.mainloop()
